<?php defined('SYSPATH') or die('No direct access allowed.');

class Model_Api_Standard_Ship
{
    private static $_typeid = 104;

    /**
     * 参数解析
     * @param $params
     */
    public static function search_result($params, $keyword, $currentpage, $pagesize = '10')
    {
        $destPy = $params['destpy'];
        $dayId = intval($params['dayid']);
        $priceId = intval($params['priceid']);
        $sortType = intval($params['sorttype']);
        $startcityId = intval($params['startcityid']);
        $attrId = $params['attrid'];
        $shipid = intval($params['shipid']);
        $page = $currentpage;
        $page = $page ? $page : 1;


        $value_arr = array();
        $where = " WHERE a.ishidden=0 ";
        //按目的地搜索
        if ($destPy && $destPy != 'all')
        {
            $destId = DB::select('id')->from('destinations')->where('pinyin', '=', $destPy)->execute()->get('id');
            $where .= " AND FIND_IN_SET('$destId',a.kindlist) ";
        }
        //天数
        if ($dayId)
        {

            if (Model_Ship_Line::is_last_day($dayId))
            {
                $where .= " AND a.lineday>='$dayId'";
            }
            else
            {
                $where .= " AND a.lineday='$dayId'";
            }

        }
        if($shipid)
        {
            $where .= " AND a.shipid='$shipid' ";
        }
        //价格区间
        if ($priceId)
        {

            $priceArr = DB::select()->from('ship_line_pricelist')->where('id', '=', $priceId)->execute()->current();
            $where .= " AND a.price BETWEEN {$priceArr['lowerprice']} AND {$priceArr['highprice']} ";
        }
        //排序
        $orderBy = "";
        if (!empty($sortType))
        {
            if ($sortType == 1)//价格升序
            {
                $orderBy = "  a.price ASC,";
            }
            else if ($sortType == 2) //价格降序
            {
                $orderBy = "  a.price DESC,";
            }
            else if ($sortType == 3) //销量降序
            {
                $orderBy = " sellnum DESC,";
            }
            else if ($sortType == 4)//推荐
            {
                $orderBy = " a.shownum DESC,";
            }
            /*  else if($sortType==5) //满意度
              {
                  $orderBy = " a.shownum desc,";
              }*/
        }

        //关键词
        if (!empty($startcityId))
        {
            $where .= " AND a.startcity=$startcityId ";
        }

        //按属性
        if (!empty($attrId))
        {
            $where .= Product::get_attr_where($attrId);
        }


        //按关键词
        if (!empty($keyword))
        {
            $value_arr[':keyword'] = '%' . $keyword . '%';
            $where .= " AND a.title like :keyword ";
        }

        $offset = (intval($page) - 1) * $pagesize;


        $orderBy = empty($orderBy) ? " IFNULL(b.displayorder,9999) ASC, " : $orderBy;
        //查询真实购买量
        $sell_where = " LEFT JOIN (SELECT COUNT(*) as s_num,productautoid FROM `sline_member_order` WHERE typeid=".self::$_typeid." GROUP BY productautoid) AS s ON s.productautoid=a.id";
        $files = ",(IFNULL(a.bookcount,0)+IFNULL(s.s_num,0)) AS sellnum";
        //如果选择了目的地
        if (!empty($destId))
        {
            $sql = "SELECT a.*{$files} FROM `sline_ship_line` a ";
            $sql .= "LEFT JOIN `sline_kindorderlist` b ";
            $sql .= "ON (a.id=b.aid AND b.typeid=".self::$_typeid." AND a.webid=b.webid AND b.classid=$destId)";
            $sql .= $sell_where;
            $sql .= $where;
            $sql .= "ORDER BY {$orderBy} a.modtime DESC,a.addtime DESC ";
            //$sql.= "LIMIT {$offset},{$pagesize}";

        }
        else
        {
            $sql = "SELECT a.*{$files} FROM `sline_ship_line` a ";
            $sql .= "LEFT JOIN `sline_allorderlist` b ";
            $sql .= "ON (a.id=b.aid AND b.typeid=".self::$_typeid." AND a.webid=b.webid)";
            $sql .= $sell_where;
            $sql .= $where;
            //$sql.= "ORDER BY IFNULL(b.displayorder,9999) ASC,{$orderBy}a.modtime DESC,a.addtime DESC ";
            $sql .= "ORDER BY {$orderBy} a.modtime DESC,a.addtime DESC ";
            //$sql.= "LIMIT {$offset},{$pagesize}";


        }

        //计算总数
        $totalSql = "SELECT count(*) as dd " . strchr($sql, " FROM");
        $totalSql = str_replace(strchr($totalSql, "ORDER BY"), '', $totalSql);//去掉order by


        $totalN = DB::query(1, $totalSql)->parameters($value_arr)->execute()->as_array();
        $totalNum = $totalN[0]['dd'] ? $totalN[0]['dd'] : 0;

        //数据量大时的优化方法,数据量小时不推荐使用此方法
        //$idWhere = "SELECT id FROM `sline_line` ORDER BY id limit $offset, 1";
        //$sql = str_replace("WHERE","WHERE a.id>($idWhere) AND",$sql);
        //$sql.= "LIMIT {$pagesize}";

        $sql .= "LIMIT {$offset},{$pagesize}";



        $arr = DB::query(1, $sql)->parameters($value_arr)->execute()->as_array();
        foreach ($arr as &$v)
        {

            $price_info = Model_Ship_Line::get_minprice($v['id'], array('info'=>$v),1);
            $v['price'] = $price_info['price'];
            $v['storeprice'] = $price_info['storeprice'];


            $v['attrlist'] = Model_Ship_Line::line_attr($v['attrid']);
            $v['startcity_name'] = Model_Startplace::start_city($v['startcity']);
            $v['commentnum'] = Model_Comment::get_comment_num($v['id'], self::$_typeid); //评论次数
            //$v['sellnum'] = Model_Member_Order::get_sell_num($v['id'],  self::$typeid) + intval($v['bookcount']); //销售数量

            $v['url'] = Common::get_web_url($v['webid']) . "/ship/show_{$v['aid']}.html";
            $v['litpic'] = Common::img($v['litpic']);
            $v['litpic'] = Model_Api_Standard_System::reorganized_resource_url($v['litpic']);
            $v['iconlist'] = Product::get_ico_list($v['iconlist']);
            $v['starttime'] = Model_Ship_Line::get_many_starttime($v['id'],1);
            $v['passed_destnames'] = Model_Ship_Line_Jieshao::get_passed_destlist($v['id']);
            $v['score'] = St_Functions::get_satisfy(self::$_typeid, $v['id'], $v['satisfyscore']);
        }
        $out = array(
            'total' => $totalNum,
            'list' => $arr,
            'is_finished'=>count($arr)<$pagesize?true:false  //是否是最后的数据
        );
        return $out;

    }
    public static function detail($id,$userid)
    {

        $info = DB::select()->from('ship_line')->where('id', '=', $id)->execute()->current();
        //seo
        $seo_info = Product::seo($info);
        $info['seo_info'] = $seo_info;
        //产品图片
        $piclist = Product::pic_list($info['piclist']);
        $p = array();
        foreach ($piclist as &$pic)
        {
            $pi = Model_Api_Standard_System::reorganized_resource_url($pic[0]);
            array_push($p, $pi);
        }
        $info['piclist'] = $p;
        $info['attrlist'] = Model_Ship_Line::line_attr($info['attrid']);

        $info['litpic'] = Model_Api_Standard_System::reorganized_resource_url( $info['litpic']);
        //最低价
        $info['priceinfo'] = Model_Ship_Line::get_minprice($info['id'], array('info', $info), 1);


        //点评数
        $info['commentnum'] = Model_Comment::get_comment_num($info['id'], self::$_typeid);
        //销售数量
        $info['sellnum'] = Model_Member_Order::get_sell_num($info['id'],  self::$_typeid) + intval($info['bookcount']);
        //产品编号
        $info['series'] = St_Product::product_series($info['id'],  self::$_typeid);
        //产品图标
        $info['iconlist'] = Product::get_ico_list($info['iconlist']);

        $info['startcity_name'] = Model_Startplace::start_city($info['startcity']);
        //供应商
        $info['suppliers']=null;
        if($info['supplierlist'])
        {
            $info['suppliers'] = DB::query(1, "SELECT suppliername FROM `sline_supplier` WHERE id={$info['supplierlist']}")->execute()->current();
        }
        //最新航线
        $info['lastest_line'] = Model_Ship_Line::get_starttime($info['id']);
        $info['schedule_name'] = DB::select('title')->from('ship_schedule')->where('id', '=', $info['scheduleid'])->execute()->get('title');
        $info['satisfyscore'] = St_Functions::get_satisfy( self::$_typeid, $info['id'], $info['satisfyscore']);

        $info['day_list'] = self::get_book_day_list($info['id'],1,4);

        $info['is_more_date'] = count( $info['day_list'])>3?1:0;

        $info['detail_list'] = self::get_content($info);
        $info['jieshao_list'] = Model_Ship_Line::jieshao($info['id'],$info['lineday']);

        foreach($info['jieshao_list'] as &$jieshao)
        {
            $jieshao['content'] = Model_Api_Standard_Xcx::filter_content($jieshao['content']);
        }


        //扩展字段信息
        $extend_info = ORM::factory('ship_line_extend_field')
            ->where("productid=" . $info['id'])
            ->find()
            ->as_array();

        $info['extend_info'] = $extend_info;


        //套餐信息
       // $info['suit_info'] = Model_Ship_Line::suit($info['id']);

        //租车详情内容
        $params = array(
            'typeid'        => self::$_typeid,
            'productinfo'   => $info,
            'onlyrealfield' => 1,
            'pc'            => 0,

        );
      //  $info['detail_list'] = self::get_content($params);

        // 更加ID查询可用的优惠券
        if(St_Functions::is_normal_app_install('coupon'))
        {
            $info['coupon_list'] = Model_Coupon::get_product_coupon_list($info['id'],self::$_typeid);
        }


        //分销赚取的金额
        if(St_Functions::is_normal_app_install('mobiledistribution'))
        {
            if(!empty($userid))
            {
                $fenxiao = DB::select()->from('fenxiao')->where("memberid",'=',$userid)->execute()->current();
                $fxgroupid = DB::select('fxgroupid')->from('fenxiao')->where("memberid",'=',$userid)->execute()->current();
                $commission_type = Model_Fenxiao_Config::get_val('cfg_fenxiao_commission_type_'.$params['typeid'],$fxgroupid['fxgroupid']);
                if($commission_type==1)
                {
                    $commission_rate = Model_Fenxiao::get_commission_rate($params['typeid'],$info['id'],$fxgroupid['fxgroupid']);
                    $v['commission'] =$commission_rate[0]*100;
                    $v['commission'] = empty($v['commission'])?0:$v['commission'];
                    $v['commission'] .='%';
                    $v['profit'] = $info['price']*$commission_rate[0];
                }
                else if($commission_type==2)
                {
                    $commission_rate = Model_Fenxiao::get_commission_rate_platform($params['typeid'],$info['id'],$fxgroupid['fxgroupid']);
                    $v['commission'] =$commission_rate[0]*100;
                    $v['commission'] = empty($v['commission'])?0:$v['commission'];
                    $v['commission'] .='%';
                    $temp_order = array('typeid'=>$params['typeid'],'productautoid'=>$info['id'],'totalprice'=>$info['price'],'dingnum'=>1);
                    $platform_price = Model_Member_Order_Compute::caculate_platform_commission($temp_order);
                    $platform_price = $platform_price==0? $info['price']:$platform_price;
                    $v['profit'] = $platform_price*$commission_rate[0];
                }
                else
                {
                    $commission_cash = Model_Fenxiao::get_commission_cash_line($params['typeid'],$info['id'],$fxgroupid['fxgroupid']);
                    $v['commission'] = $commission_cash[0]['adult'];
                    $v['commission'] = empty($v['commission'])?0:$v['commission'];
                    $v['profit'] = $v['commission'];
                }
                $info['profit'] = $v['profit'];
                $info['is_fenxiao'] = !empty($fenxiao) && $fenxiao['status']==1?true:false;
            }
        }
        return $info;
    }
    //获取普通排序的轮船列表
    public static function get_ship_list($page,$page_size=10)
    {
        $page = $page<1?1:$page;
        $offset = ($page-1)*$page_size;
        $sql = "SELECT * FROM `sline_ship` where ishidden=0 ORDER BY displayorder asc,addtime desc ";
        $sql .= "LIMIT {$offset},{$page_size}";
        $arr = DB::query(Database::SELECT, $sql)->execute()->as_array();
        foreach($arr as &$v)
        {
            $v['litpic'] = Common::img($v['litpic']);
            $v['litpic'] = Model_Api_Standard_System::reorganized_resource_url($v['litpic']);
        }
        return $arr;
    }

    /**
     * @param $params
     * @return Array
     * 天数读取
     */

    public static function day_list()
    {

        $suit = ORM::factory('ship_line_day')->get_all();
        $autoindex = 1;
        foreach ($suit as &$r)
        {
            $number = substr($r['title'], 0, 2);
            $r['number'] = $number;
            $arr = array("零", "一", "二", "三", "四", "五", "六", "七", "八", "九");
            if (strlen($number) == 1)
            {
                $result = $arr[$number];
            }
            else
            {
                if ($number == 10)
                {
                    $result = "十";
                }
                else
                {
                    if ($number < 20)
                    {
                        $result = "十";
                    }
                    else
                    {
                        $result = $arr[substr($number, 0, 1)] . "十";
                    }
                    if (substr($number, 1, 1) != "0")
                    {
                        $result .= $arr[substr($number, 1, 1)];
                    }
                }
            }

            if ($autoindex == count($suit))
            {
                $r['title'] = $result . "日游以上";
            }
            else
            {
                $r['title'] = $result . "日游";
            }
            $autoindex++;

        }
        return $suit;
    }


    public static function price_list()
    {
        $suit = ORM::factory('ship_line_pricelist')
            ->where('lowerprice', '>=', 0)
            ->order_by('lowerprice', 'asc')
            ->get_all();
        foreach ($suit as &$row)
        {
            if ($row['lowerprice'] == 0 && $row['highprice'] != 0)
            {
                $row['title'] = Currency_Tool::symbol() . $row['highprice'] . '以下';
            }
            else if ($row['highprice'] == '' || $row['highprice'] == 0)
            {
                $row['title'] = Currency_Tool::symbol() . $row['lowerprice'] . '以上';
            }
            else if ($row['lowerprice'] != '' && $row['highprice'] != '')
            {
                $row['title'] = Currency_Tool::symbol() . $row['lowerprice'] . '-' . Currency_Tool::symbol() . $row['highprice'];
            }
        }
        return $suit;
    }

    //获取设施分类
    public static function facility_kind($shipid,$page=1,$pagesize=100)
    {

        $shipid = intval($shipid);
        $page = $page<1?1:$page;
        $offset = ($page-1)*$pagesize;

        if (!empty($shipid))
        {
            $sql = " SELECT DISTINCT a.* FROM sline_ship_facility_kind a inner join sline_ship_facility b on a.id=b.kindid where b.shipid='{$shipid}' ORDER BY  displayorder LIMIT {$offset},{$pagesize}";
        }
        else
        {
            $sql = "SELECT * FROM sline_ship_facility_kind  ORDER BY  displayorder LIMIT {$offset},{$pagesize}";
        }
        $list = DB::query(Database::SELECT, $sql)->execute()->as_array();
        return $list;
    }



    //获取舱房分类
    public static function room_kind($shipid,$page=1,$pagesize=100)
    {
        $page = $page<1?1:$page;
        $offset = ($page-1)*$pagesize;


        if (!empty($shipid))
        {
            $sql = " SELECT a.*,sum(b.num) as roomnum FROM sline_ship_room_kind a inner join sline_ship_room b on a.id=b.kindid where b.shipid='{$shipid}' GROUP BY a.id  ORDER BY  displayorder LIMIT {$offset},{$pagesize}";
        }
        else
        {
            $sql = "SELECT * FROM sline_ship_room_kind  ORDER BY  displayorder LIMIT {$offset},{$pagesize}";
        }
        $list = DB::query(Database::SELECT, $sql)->execute()->as_array();

        foreach($list as &$row)
        {
            if(!empty($shipid))
            {
                $piclist =explode(',',$row['piclist']);
                $p = array();
                foreach ($piclist as &$pic)
                {
                    $pi = Model_Api_Standard_System::reorganized_resource_url($pic[0]);
                    array_push($p, $pi);
                }
                $row['piclist'] = $p;
                $row['litpic'] = DB::query(Database::SELECT,"select litpic from sline_ship_room where shipid='{$shipid}' and kindid='{$row['id']}' and litpic!='' and litpic is not null limit 1")->execute()->get('litpic');
                $row['litpic'] = Common::img($row['litpic']);
                $row['litpic'] = Model_Api_Standard_System::reorganized_resource_url($row['litpic']);
                $row['num'] =  DB::query(Database::SELECT,"select count(*) as num from sline_ship_room where shipid='{$shipid}' and kindid='{$row['id']}'")->execute()->get('num');
            }

        }

        return $list;
    }

    //获取舱房分类
    public static function room($shipid,$kindid=0,$page=1,$pagesize=100)
    {

        $shipid = intval($shipid);
        $kindid = intval($kindid);

        $page = $page<1?1:$page;
        $offset = ($page-1)*$pagesize;

        $where = " WHERE shipid='{$shipid}' ";
        $where .= !empty($kindid) ? " AND kindid='{$kindid}' " : '';
        $sql = "SELECT * FROM sline_ship_room {$where} ORDER BY  displayorder LIMIT {$offset},{$pagesize}";
        $list = DB::query(Database::SELECT, $sql)->execute()->as_array();
        foreach($list as &$v)
        {
            $v['litpic'] = Common::img($v['litpic']);
            $v['litpic'] = Model_Api_Standard_System::reorganized_resource_url($v['litpic']);
            $v['floors_str'] = Model_Ship_Floor::get_names_bystr($v['floors']);

            $piclist =explode(',',$v['piclist']);
            $p = array();
            foreach ($piclist as &$pic)
            {
                if($pic!='')
                {
                    $pi = Model_Api_Standard_System::reorganized_resource_url($pic);
                    array_push($p, $pi);
                }
            }
            $v['piclist'] = $p;
        }
        return $list;
    }

    //获取楼层
    public static function floor($shipid,$kindid=0,$page=1,$pagesize=100)
    {

        $shipid = intval($shipid);
        $page = $page<1?1:$page;
        $offset = ($page-1)*$pagesize;
        $sql = "SELECT * FROM sline_ship_floor WHERE shipid='{$shipid}' ORDER BY  displayorder LIMIT {$offset},{$pagesize}";
        $list = DB::query(Database::SELECT, $sql)->execute()->as_array();
        foreach ($list as &$v)
        {
            $facility_names =  Model_Ship_Facility::get_names_byfloor($v['id']);
            $room_names = Model_Ship_Room::get_names_byfloor($v['id']);
            $v['facilityname_arr'] = empty($facility_names)?null:explode(',', $facility_names);
            $v['roomname_arr'] = empty($room_names)?null:explode(',', $room_names);

        }
        return $list;
    }

    //获取设施列表
    public static function facility($shipid,$kindid=0,$page=1,$pagesize=100)
    {
        $shipid = intval($shipid);
        $page = $page<1?1:$page;
        $offset = ($page-1)*$pagesize;
        $offset = intval($offset);
        $kindid = intval($kindid);
        if (empty($shipid))
            return null;
        $where = " WHERE shipid='{$shipid}' ";
        $where .= !empty($kindid) ? " AND kindid='{$kindid}' " : '';
        $sql = "SELECT * FROM sline_ship_facility {$where} ORDER BY  displayorder LIMIT {$offset},{$pagesize}";
        $list = DB::query(Database::SELECT, $sql)->execute()->as_array();
        foreach($list as &$v)
        {
            $v['litpic'] = Common::img($v['litpic']);
            $v['litpic'] = Model_Api_Standard_System::reorganized_resource_url($v['litpic']);
            $v['floors_names'] = Model_Ship_Floor::get_names_bystr($v['floors']);
        }
        return $list;
    }


    public static function startplace($offset=0,$size=30)
    {
        $sql="SELECT a.*,a.cityname as title FROM `sline_startplace` a left join sline_ship_startplace b on a.id=b.startplace_id WHERE a.isopen=1 and b.isopen=1 AND pid!=0 ORDER BY b.displayorder ASC,a.displayorder ASC LIMIT $offset,$size";
        $ar = DB::query(1,$sql)->execute()->as_array();
        return $ar;
    }

    public static function get_book_day_list($shiplineid,$page=1,$pagesize=10)
    {

        $page = $page<1?1:$page;
        $offset = ($page-1)*$pagesize;

        $info = DB::select('islinebefore', 'linebefore')->from('ship_line')->where('id', '=', $shiplineid)->execute()->current();
        $ext['islinebefore'] = $info['islinebefore'];
        $ext['linebefore'] = $info['linebefore'];
        $startdate = 0;
        if ($ext['islinebefore']) {
            $startdate = date('Y-m-d', strtotime("+{$ext['linebefore']} days", time()));
        }
        $starttime = empty($startdate)? time():strtotime($startdate);

        $suitfields = "a.basicprice,a.profit,a.price,a.storeprice,a.number,a.suitid";
        $sql = "select {$suitfields},a.price as minprice,a.price/z.peoplenum as avgprice,b.starttime as day,b.endtime   from sline_ship_line_suit_price a inner join sline_ship_schedule_date b";
        $sql.=" on a.dateid=b.id and a.scheduleid=b.scheduleid ";
        $sql.=" inner join (select x.id as suitid,y.peoplenum from  sline_ship_line_suit x inner join sline_ship_room y on x.roomid=y.id) z on a.suitid=z.suitid ";

        $sql.="inner join sline_ship_line c ";
        $sql.=" on a.lineid=c.id and a.shipid=c.shipid and a.scheduleid=c.scheduleid ";
        $sql.=" where b.starttime>={$starttime}  and a.price>0 and c.id={$shiplineid} order by b.starttime asc,avgprice asc";
        //$sql.=$pagesize>0 ?" limit {$offset},{$pagesize}":'';

        $list = DB::query(Database::SELECT,$sql)->execute()->as_array();

        $newlist = array();
        $days = array();
        foreach($list as $v)
        {

            if(count($newlist)>=$pagesize)
            {
                break;
            }

            if(in_array($v['day'],$days))
            {
                continue;
            }
            $days[]=$v['day'];
            $roomid = DB::select('roomid')->from('ship_line_suit')->where('id','=',$v['suitid'])->execute()->get('roomid');
            $peoplenum = DB::select('peoplenum')->from('ship_room')->where('id','=',$roomid)->execute()->get('peoplenum');
            $peoplenum = empty($peoplenum)?1:$peoplenum;
            $v['minprice'] =  Currency_Tool::price(floor($v['minprice']/$peoplenum));
            $v['price'] =  Currency_Tool::price($v['price']);
            $v['date_fmt'] = date('Y-m-d',$v['day']);
            $v['date_year'] = date('Y',$v['day']);
            $v['date_md'] = date('m-d',$v['day']);

            $v['date_end_fmt'] = date('Y-m-d',$v['endtime']);
            $v['date_end_year'] = date('Y',$v['endtime']);
            $v['date_end_md'] = date('m-d',$v['endtime']);
            $newlist[] = $v;
        }
        return $newlist;
    }

    public static function get_content($productinfo)
    {

        $arr = DB::select('columnname', 'chinesename', 'isrealfield')->from('ship_line_content')->order_by('displayorder', 'asc')->execute()->as_array();

        $productid = $productinfo['id'];//产品id
        //邮轮扩展
        $ar = DB::select()->from('ship_line_extend_field')->where('productid','=',$productid)->execute()->as_array();

        $list = array();
        foreach ($arr as $v)
        {
            if ($v['columnname'] == 'tupian')
            {
                continue;
            }
            if ($v['isrealfield'] == 1)
            {
                $content = !empty($productinfo[$v['columnname']]) ? $productinfo[$v['columnname']] : $ar[0][$v['columnname']];
                $content = $content ? $content : '';
            }
            else
            {

                $content = $productinfo['id'];
            }
            //行程附件
            if ($v['columnname'] == 'linedoc')
            {
                if ('array' == strtolower($content))
                {
                    $content = null;
                }
            }
            $a = array();
            $a['columnname'] = $v['columnname'];
            $a['chinesename'] = $v['chinesename'];

            $a['content'] =  Model_Api_Standard_Xcx::filter_content($content); //针对PC/手机版选择是否去样式.

            //var_dump($a,13246798);
            $list[] = $a;

        }
        return $list;
    }


}